from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from models import User, db
from forms.admin import UserForm

admin_bp = Blueprint('admin', __name__)

@admin_bp.before_request
def admin_required():
    if not current_user.is_authenticated or current_user.role != 'admin':
        flash('只有管理员可以访问该页面！', 'danger')
        return redirect(url_for('index'))

@admin_bp.route('/users')
@login_required
def users():
    page = request.args.get('page', 1, type=int)
    users = User.query.order_by(User.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False
    )
    return render_template('admin/users.html', users=users)

@admin_bp.route('/users/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit_user(id):
    user = User.query.get_or_404(id)
    form = UserForm(obj=user)
    
    if form.validate_on_submit():
        # 不允许修改最后一个管理员的角色
        if user.role == 'admin' and form.role.data != 'admin':
            admin_count = User.query.filter_by(role='admin').count()
            if admin_count <= 1:
                flash('系统至少需要一个管理员！', 'danger')
                return redirect(url_for('admin.users'))
        
        user.username = form.username.data
        user.email = form.email.data
        user.name = form.name.data
        user.role = form.role.data
        user.bio = form.bio.data
        
        db.session.commit()
        flash('用户信息已更新！', 'success')
        return redirect(url_for('admin.users'))
        
    return render_template('admin/edit_user.html', form=form, user=user)

@admin_bp.route('/users/<int:id>/delete', methods=['POST'])
@login_required
def delete_user(id):
    user = User.query.get_or_404(id)
    
    # 不允许删除最后一个管理员
    if user.role == 'admin':
        admin_count = User.query.filter_by(role='admin').count()
        if admin_count <= 1:
            flash('系统至少需要一个管理员！', 'danger')
            return redirect(url_for('admin.users'))
    
    # 不允许删除自己
    if user.id == current_user.id:
        flash('不能删除自己的账户！', 'danger')
        return redirect(url_for('admin.users'))
    
    db.session.delete(user)
    db.session.commit()
    flash('用户已删除！', 'success')
    return redirect(url_for('admin.users')) 